<template>
  <div id="render">
    <v-overlay
      :absolute="absolute"
      :value="overlay"
    >
      <v-progress-linear
        rounded
        style="width: 400px"
        :value="progress">
      </v-progress-linear>
    </v-overlay>
  </div>
</template>

<script>
  import * as th from 'three'
  import IndexDBWrapper from 'indexdbwrapper'
  import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls'

  export default {
    // eslint-disable-next-line vue/multi-word-component-names
    name: 'Render',
    data() {
      return {
        scene: null,
        camera: null,
        renderer: null,
        axesHelper: null,
        orbitControls: null,
        pointCloud: null,
        db: null,
        absolute: true,
        overlay: false,
        progress: 0
      }
    },
    mounted() {
      let that = this
      if (this.db == null) {
        this.db = new IndexDBWrapper('db', 1)
      }
      console.log('render db link', this.db)
      // 初始化
      setTimeout(function() {
        that.init()
      }, 1)
      // 循环
      this.run()
    },
    methods: {
      init: function() {
        //获取容器
        let box = document.getElementById('render')
        let renderHeight = window.sessionStorage.getItem('renderHeight')
        //创建场景
        this.scene = new th.Scene()
        // 初始化相机
        this.camera = new th.PerspectiveCamera(40, box.offsetWidth / renderHeight, 0.1, 10000)
        // 3 2 2
        this.camera.position.z = 10
        this.camera.position.x = 3
        this.camera.position.y = 2.5
        // 初始化辅助参考坐标
        this.axesHelper = new th.AxesHelper(3, 2.5, 0)
        this.scene.add(this.axesHelper)
        // 初始化renderer
        this.renderer = new th.WebGLRenderer({antialias: true})
        this.renderer.setPixelRatio(window.devicePixelRatio)
        this.renderer.setSize(box.offsetWidth - 1, renderHeight)
        // 插入html
        box.appendChild(this.renderer.domElement)
        // this.setKeyEvents()
        // this.setMouseEvents()
      },
      // setKeyEvents: function() {
      //   let that = this
      //   window.addEventListener('keydown', function(e) {
      //     switch (e.key) {
      //       case'd':
      //       case'D':
      //         that.camera.position.x += 0.5
      //         break
      //       case'a':
      //       case'A':
      //         that.camera.position.x -= 0.5
      //         break
      //       case'w':
      //       case'W':
      //         that.camera.position.y += 0.5
      //         break
      //       case's':
      //       case'S':
      //         that.camera.position.y -= 0.5
      //         break
      //     }
      //     console.log(that.camera.position.x, that.camera.position.y, that.camera.position.y)
      //   })
      // },
      // setMouseEvents: function() {
      //   let that = this
      //   let render = document.getElementById('render')
      //   // 添加鼠标滚轮事件
      //   render.addEventListener('mousewheel', function(e) {
      //     if (e.deltaY < 0) {
      //       if (that.camera.position.z - 0.5 > 0) {
      //         that.camera.position.z -= 0.5
      //       }
      //     } else {
      //       that.camera.position.z += 0.5
      //     }
      //     // console.log(that.camera.position.z)
      //     e.preventDefault()
      //   })
      //   // 添加鼠标拖拽事件
      //   render.addEventListener('mousedown', function(e) {
      //     that.downPosition.set(e.offsetX, e.offsetY)
      //     that.down = true
      //   })
      //   render.addEventListener('mousemove', function(e) {
      //     if (that.down) {
      //       let diffX = e.offsetX - that.downPosition.x
      //       let diffY = e.offsetY - that.downPosition.y
      //       let arg = Math.PI / 4
      //       that.pointCloud.rotateX(arg * diffY / 10000)
      //       that.pointCloud.rotateY(arg * diffX / 10000)
      //     }
      //   })
      //   render.addEventListener('mouseup', function() {
      //     that.down = false
      //   })
      // },
      run: function() {
        requestAnimationFrame(this.run)
        this.renderer.render(this.scene, this.camera)
        if (this.orbitControls != null) {
          this.orbitControls.update()
        }
      },
      createPoints(i, id) {
        this.overlay = true
        this.progress = 0
        this.scene.remove(this.pointCloud)
        // let index = this.$parent.$parent.$parent
        console.log('createPoints')
        let that = this
        let points
        let haveColor
        let length
        // 从db中找id对应的
        if (that.db != null) {
          this.db.open()
          console.log('open db before getKey', this.db)
          this.db.get('t1', id)
            .then(res => {
              console.log('get res', res)
              // 设置遮罩层
              // res为indexedDB获得的结果
              points = res.arr_pred
              haveColor = true
              length = points.length
              // 创建几何对象
              let geometry = new th.BufferGeometry()
              let vertices = []
              // 插入点
              for (let i = 0; i < length; i++) {
                for (let j = 0; j < 3; j++) {
                  vertices.push(parseFloat(points[i][j]))
                }
              }
              console.log('vertices', vertices)
              geometry.setAttribute('position', new th.Float32BufferAttribute(vertices, 3))
              if (haveColor) {
                that.progress = 50
              } else {
                that.progress = 100
              }

              // 如果有颜色信息，插入颜色
              console.log('th.VertexColors', th.VertexColors)
              let material
              let colors = []
              if (haveColor) {
                for (let i = 0; i < length; i++) {
                  for (let j = 3; j < 6; j++) {
                    colors.push(parseFloat(points[i][j]) / 255)
                  }
                }
                console.log('colors', colors)
                geometry.setAttribute('color', new th.Float32BufferAttribute(colors, 3))
                setTimeout(function() {
                  that.progress = 100
                }, 100)
                material = new th.PointsMaterial({
                  size: 3,
                  sizeAttenuation: false,
                  vertexColors: th.VertexColors,
                  transparent: true
                })
              } else {
                material = new th.PointsMaterial({
                  size: 10,
                  sizeAttenuation: false,
                  transparent: true
                })
              }
              that.pointCloud = new th.Points(geometry, material)
              that.scene.add(that.pointCloud)
              console.log('points', that.pointCloud)
              that.camera.position.x = that.pointCloud.geometry.attributes.position.array[0]
              that.camera.position.y = that.pointCloud.geometry.attributes.position.array[1]
              that.camera.position.z = that.pointCloud.geometry.attributes.position.array[2]
              that.orbitControls = null
              that.orbitControls = new OrbitControls(that.camera, that.renderer.domElement)
              console.log('created')
              setTimeout(function() {
                that.overlay = false
              }, 500)
              that.$message.success('点云渲染成功！')
              that.db.close()
            })
            .catch(err => {
              that.overlay = false
              that.$message.error('点云渲染失败' + err)
            })
        }
      }
    }
  }
</script>

<style scoped>
  #render {
    width: 100%;
    height: 100%;
  }
</style>
